//
//  FCUserReg.swift
//  miaoyin
//
//  Created by David on 2017/2/24.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

final class FCUserReg: NSObject {
    static let shared = FCUserReg()
    private override init() {}
    
    //username=&password&code=&schoolId=&year=&univsId=
    var username: String?
    var password: String?
    var code: String?
    var schoolId: String?
    var year: String?
    var univsId: String?
    var nickName: String?
    var avatarImg: Data?
    var sex: String?
    var isRegisterStarted : Bool{
        get{
            return registering
        }
    }
    private var registering = false
    
    func startRegister(){
        registering = true
        username = ""
        password = ""
        code = ""
        schoolId = ""
        year = ""
        univsId = ""
        
        nickName = ""
        sex = ""
    }
    
    func initCommitUserInfo(successHandler: @escaping (Any?) -> Void, failedHandler: @escaping (Any?) -> Void){
        if isRegisterStarted{
            var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=index&a=editInfo")!)
            resq.httpMethod = "POST"
            resq.setValue("multipart/form-data; boundary=AaB03x", forHTTPHeaderField: "Content-Type")
            //resq.httpBody = "nickname=\(nickName!)&sex=男(性别) file=face(头像上传字段) schoolId=(专业id) univsId(学校id) year".data(using: .utf8)
            var postData = Data()
            
            
            var formDataStr = ""
            if nickName != "" {
                formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"nickname\";\r\n\r\n\(nickName!)\r\n"
            }else{
                if username != "" {
                    formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"nickname\";\r\n\r\n\(username!)\r\n"
                }
            }
            if sex != "" {
                formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"sex\";\r\n\r\n\(sex!)\r\n"
            }
            if schoolId != "" {
                formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"schoolId\";\r\n\r\n\(schoolId!)\r\n"
            }
            if univsId != "" {
                formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"univsId\";\r\n\r\n\(univsId!)\r\n"
            }
            if year != "" {
                formDataStr += "--AaB03x\r\nContent-Disposition: form-data; name=\"year\";\r\n\r\n\(year!)\r\n"
            }
            postData.append(formDataStr.data(using: .utf8)!)
            print(String(data: postData, encoding: .utf8) ?? "data nil")
//            if avatarImg != nil{
//                postData.append("--AaB03x\r\nContent-Disposition: form-data; name=\"face\"; filename=\"filename.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
//                postData.append(avatarImg!)
//                postData.append("\r\n--AaB03x--\r\n".data(using: .utf8)!)
//            }
            resq.setValue("\(postData.count)", forHTTPHeaderField: "Content-Length")
            resq.httpBody = postData
            
            URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                do{
                    if err != nil {
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    
//                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    
                    
                    successHandler(data)
                    
                    self.registering = false
                    
                    self.nickName = ""
                    self.sex = ""
                    self.schoolId = ""
                    self.univsId = ""
                    self.year = ""
                    self.avatarImg = nil
                    
                }catch let ex{
                    print(ex)
                    failedHandler("\(ex)")
                }
            }).resume()
            
        }else{
            failedHandler("RegisterNotStarted")
        }
    }
    
    /*
    func commitRegister(successHandler: @escaping (Any?) -> Void, failedHandler: @escaping (Error?) -> Void){
        if isRegisterStarted{
            var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userRegister")!)
            resq.httpMethod = "POST"
            //username=&password&code=&schoolId=&year=&univsId=
            resq.httpBody = "username=\(username!)&password=\(password!)&code=\(code!)&schoolId=\(schoolId!)&year=\(year!)&univsId=\(univsId!)".data(using: .utf8)
            print("username=\(username!)&password=\(password!)&code=\(code!)&schoolId=\(schoolId!)&year=\(year!)&univsId=\(univsId!)")
            URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data not utf8")
                    successHandler(data)
                }catch let ex{
                    print(ex)
                    DispatchQueue.main.async {
                        failedHandler(ex)
                    }
                    
                }
                
            }.resume()
            registering = false
        }
    }
    */
    
    var wodeVC: WodeViewController?{
        return (UIApplication.shared.delegate as? AppDelegate)?.wodeVC
    }
}
